package com.i2863.tools.weixinmp.task;

import com.i2863.tools.weixinmp.domain.Weixin;
import com.i2863.tools.weixinmp.util.HttpSessionUtils;
import com.i2863.tools.weixinmp.util.RegExUtil;
import com.i2863.tools.weixinmp.util.SunProxyUtil;
import com.i2863.tools.weixinmp.util.UrlUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component("weixinNoticeTask")
public class WeixinMpNotice {

    private static final Logger logger = LoggerFactory.getLogger(WeixinMpNotice.class);
    public static CloseableHttpClient httpClient = HttpSessionUtils.buildHttpClient();

    public static Map<String, Object> parseWeixin(String code, int page) throws UnsupportedEncodingException {
        List<Weixin> weixinList = new ArrayList<Weixin>();
        CloseableHttpClient client = httpClient;
        Map<String, Object> map = new HashMap<String, Object>();
        String firstUrl = "http://weixin.sogou.com/weixin?type=1&query=" + URLEncoder.encode(code, "UTF-8")
                + "&ie=utf8&page=" + page;
        for (int i = 1; i < 5; i++) {
            try {
                String content = HttpSessionUtils.httpGet(client, firstUrl);
                if (content.indexOf("您的访问过于频繁") >= 0) {
                    logger.warn("访问过于频繁");
                    if (i < 4) {
                        client = HttpSessionUtils.buildHttpClient(SunProxyUtil.getHttpHost(firstUrl));
                    }
                    continue;
                }
                if (!content.contains("以下内容来自微信公众号")) {
                    if (i < 4) {
                        client = HttpSessionUtils.buildHttpClient(SunProxyUtil.getHttpHost(firstUrl));
                    }
                    continue;
                }
                Document doc = Jsoup.parse(content);
                int count = 0;
                Elements divMun = doc.select("div.mun");
                if (divMun.size() > 0) {
                    String mun = doc.select("div.mun").get(0).text();
                    String countStr = RegExUtil.getFirstValue(mun, "找到约(\\d+)条结果", 1);
                    if (countStr != null && countStr.length() > 0) {
                        count = Integer.parseInt(countStr);
                    }
                }

                Elements liss = doc.select("ul.news-list2 > li");
                if (count <= 0) {
                    count = liss.size();
                }
                for (Element li : liss) {
                    Element link = li.select("p.tit > a").get(0);
                    String href = link.attr("href");
                    final String weixinUrl = UrlUtil.joinUrl(firstUrl, href);
                    String weixinCode = li.select("label").get(0).text();
                    final String name = link.text();
                    Weixin wx = new Weixin();
                    wx.setCode(weixinCode);
                    wx.setName(name);
                    weixinList.add(wx);
                }

                map.put("data", weixinList);
                map.put("maxpage", (int) Math.ceil(count * 1.0 / 10));
                return map;
            } catch (Exception e) {
                if (i < 4) {
                    client = HttpSessionUtils.buildHttpClient(SunProxyUtil.getHttpHost(firstUrl));
                }
            }
        }
        throw new RuntimeException("连续5次失败");

    }


    public static void main(String[] args) throws UnsupportedEncodingException {
        final WeixinMpNotice product = new WeixinMpNotice();
        List<Weixin> weixinList = (List<Weixin>) product.parseWeixin("乾安", 1).get("data");
        for (Weixin w : weixinList) {
            System.out.println(w.getName() + "\t" + w.getCode() + "\t");
        }
    }


}
